package com.medaxis.hpams.sso.service.impl;


import com.medaxis.hpams.dto.global.ErrorException;
import com.medaxis.hpams.sso.constant.Constants;
import com.medaxis.hpams.sso.domain.dto.DictTypeDto;
import com.medaxis.hpams.sso.mapper.DictDataMapper;
import com.medaxis.hpams.sso.mapper.DictTypeMapper;
import com.medaxis.hpams.sso.service.DictTypeService;
import com.medaxis.hpams.sso.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictTypeServiceImpl implements DictTypeService{

    @Autowired
    DictTypeMapper dictTypeMapper;
    @Autowired
    DictDataMapper dictDataMapper;
    @Override
    public   List<DictTypeDto>  selectDictTypeList(DictTypeDto dictTypeDto) {
       return dictTypeMapper.selectDictTypeList(dictTypeDto);
    }

    @Override
    public DictTypeDto selectDictTypeById(Long id) {
        return dictTypeMapper.selectDictTypeById(id);
    }


    /**
     *根据字典类型判断数据库是否存在该数据
     * @param dicDto
     * @return
     */
    @Override
    public String checkDictTypeUnique(DictTypeDto dictDto) {
        DictTypeDto  dictTypeDto = dictTypeMapper.checkDictTypeUnique(dictDto);
        if(StringUtils.isNotNull(dictTypeDto) ){
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;

    }
//
    @Override
    public int insertDictType(DictTypeDto  dictTypeDto) {
        return  dictTypeMapper.insertDictType(dictTypeDto);
    }
//
    @Override
    public int updateDictType(DictTypeDto  dictDto) {
        return dictTypeMapper.updateDictType(dictDto);
    }

    /**
     * 删除数据类型时要判断该类型下面是否有数据
     * @param ids
     * @return
     */
    @Override
    public int deleteDictTypeByIds(Long[] ids) {
        for (Long id : ids) {
            DictTypeDto  dictType = selectDictTypeById(id);
            int count= dictDataMapper.countByDictType(dictType.getDictType());
            if(count>0){
                throw new ErrorException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
        }
        return dictTypeMapper.deleteDictTypeByIds(ids);
    }


}
